package com.kantboot.api.qiucloud.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.kantboot.util.common.exception.BaseException;
import com.qiniu.common.Constants;
import com.qiniu.common.QiniuException;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Json;
import com.qiniu.util.StringMap;
import lombok.SneakyThrows;

import java.lang.reflect.Method;

public class ApiQiniuCloudUtil {

    @SneakyThrows
    public static void sendFulltextMessageOne(String phone, String content, Auth auth) {
        String requestUrl = String.format("%s/v1/message/fulltext", "https://sms.qiniuapi.com");
        StringMap bodyMap = new StringMap();
        bodyMap.put("mobiles", new String[]{phone});
        bodyMap.put("content", content);
        // 强行使用smsManager的private方法，反射
        SmsManager smsManager = new SmsManager(auth);
        Method method = SmsManager.class.getDeclaredMethod("post", String.class, byte[].class);
        method.setAccessible(true);
        try{
            Object invoke = method.invoke(smsManager, requestUrl, Json.encode(bodyMap).getBytes(Constants.UTF_8));
        }catch (Exception e){
            // 获取异常信息
            QiniuException qiniuException = (QiniuException) e.getCause();
            JSONObject jsonObject = JSON.parseObject(qiniuException.response.bodyString());
            String error = jsonObject.getString("error");
            String message = jsonObject.getString("message");
            if (error.equals("InvalidArgument")&&message.endsWith("not match any of your templates")){
                throw BaseException.of("qiniuCloudErrCodeOfInvalidArgument","七牛云模板不存在");
            }
        }
    }

//    @SneakyThrows
//    public static void sendFulltextMessageOne(String phone, String content, Auth auth) {
//        // 构造smsManager方法
//        SmsManager smsManager = new SmsManager(auth);
//        try {
//            // 手机号
//            String[] mobile = {phone};
//            Response resp = smsManager.sendFulltextMessage(mobile, content);
//            System.out.println(resp.bodyString());
//        } catch (QiniuException e) {
//            // 获取异常信息
//            QiniuException qiniuException = (QiniuException) e.getCause();
//            JSONObject jsonObject = JSON.parseObject(qiniuException.response.bodyString());
//            String error = jsonObject.getString("error");
//            String message = jsonObject.getString("message");
//            if (error.equals("InvalidArgument")&&message.endsWith("not match any of your templates")){
//                throw BaseException.of("qiniuCloudErrCodeOfInvalidArgument","七牛云模板不存在");
//            }
//        }
//    }

}
